package com.miyake.client.datamanage;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Panel;
import com.miyake.client.DataService;
import com.miyake.client.DataServiceAsync;
import com.miyake.client.tools.EditableText;
import com.miyake.client.tools.EditableText.EditableTextHandler;

public abstract class ShowEditableText {
	private DataServiceAsync service = DataService.Util.getInstance();
	abstract protected void onTextUpdate(String nodeKey);
	
	public ShowEditableText(final NodeProperty node, Panel panel) {
		final EditableText textBox = new EditableText();
		textBox.setWidth("100%");
		panel.add(textBox);
		textBox.addEditableTextHandler(new EditableTextHandler() {
			@Override
			public void onTextUpdate(Text text) {
				setText(node.getKey(), text, service);
			}
		});
		
		service.getText(node.getKey(), new AsyncCallback<Text>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(Text result) {
				textBox.setText(result);
			}
		});
	}
	
	private void setText(final String nodeKey, Text text, DataServiceAsync service) {
		service.updateText(nodeKey, text, new AsyncCallback<Void>() {
			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(Void result) {
				onTextUpdate(nodeKey);
			}
		});
	}

}
